<template>
  <div :class="{ hidden: hidden }" class="pagination">
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :background="background"
      :layout="layout"
      :page-sizes="pageSizes"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <slot />
    </el-pagination>
  </div>
</template>

<script setup lang="ts">
defineOptions({ name: 'Pagination' });
const props = defineProps({
  total: {
    type: Number as PropType<number>,
    default: 0,
  },
  pageSizes: {
    type: Array as PropType<number[]>,
    default: () => [10, 20, 30, 50, 100],
  },
  // 如需使用默认插槽，需在 layout 中合适位置加入 slot
  layout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper',
  },
  background: {
    type: Boolean,
    default: true,
  },
  hidden: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(['pagination', 'current-change', 'size-change']);

const currentPage = defineModel('page', {
  type: Number,
  required: true,
  default: 1,
});

const pageSize = defineModel('limit', {
  type: Number,
  required: true,
  default: 10,
});

watch(
  () => props.total,
  (newVal: number) => {
    const lastPage = Math.ceil(newVal / pageSize.value);
    if (newVal > 0 && currentPage.value > lastPage) {
      currentPage.value = lastPage;
      emit('pagination', { page: currentPage.value, limit: pageSize.value });
    }
  }
);

function handleSizeChange(val: number) {
  currentPage.value = 1;
  emit('pagination', { page: currentPage.value, limit: val });
  emit('size-change', val);
}

function handleCurrentChange(val: number) {
  emit('pagination', { page: val, limit: pageSize.value });
  emit('current-change', val);
}
</script>
